package com.caine.payment.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.caine.payment.entity.Balance;
import com.caine.payment.service.IBalanceService;
import com.caine.payment.vo.OrderVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author V
 * @since 2021-01-04
 */
@RestController
@RequestMapping("/payment")
public class PaymentController {

    @Autowired
    private IBalanceService balanceService;

    @RequestMapping("pay")
    @Transactional
    public boolean pay(@RequestBody OrderVO vo) {
        Balance balance = balanceService.getOne(new LambdaQueryWrapper<Balance>().eq(Balance::getUserId, vo.getUserId()));
        if (balance != null) {
            BigDecimal multiply = vo.getCount().multiply(vo.getPrice());
            BigDecimal divide = balance.getBalance().subtract(multiply);
            int ret = divide.compareTo(BigDecimal.valueOf(0));
            if (ret >= 0) {
                balance.setBalance(divide).updateById();
                return true;
            }

        }
        throw new RuntimeException("余额不足");
    }

}
